function PlotSpecNotch(ax,sch)
% PlotSpecNotch(ax,sch)
% 
% ax = handle to axes object
% sch = schedule structure
% 
% DJS (c) 2010

if isempty(ax)
    ax = gca;
end

h = [2 4 6 8];      % hits
m = [1 3 5 7];      % misses
u = [-1 -2 -3 -4];  % uncertain
nr = -5;            % no response

rv = sch.response_vals;

kk = find(ismember(sch.writeparams,{'Buffer~1','Buffer~2'}));

% find conditions present in the data
tt = cell(size(sch.trials,1),1);
for i = 1:size(sch.trials,1)
    tt{i} = decodetrial(sch.trials(i,:),kk);
end

% compute hit-rate for each condition
thr = nan(size(sch.trials,1),1);
tur = nan(size(sch.trials,1),1);
for i = 1:length(thr)
    ind = rv(:,1) == i;
    if ~any(ind), continue; end
        
    thr(i) = sum(ismember(rv(ind,3),h));
    tur(i) = sum(ismember(rv(ind,3),u));
end

utt = unique(tt);
hr  = nan(size(utt));
ur  = nan(size(utt));
for i = 1:length(utt)
    ind = strcmp(utt{i},tt);
    
    s = sum(ismember(rv(:,1),find(ind)));
    
    if ~s, continue; end
    
    hr(i) = nansum(thr(ind)) / s;
    ur(i) = nansum(tur(ind)) / s;
end

% compute and cut out False Alarm Rate (FAR) on Catch Trials (CT)
fa = strcmp('CT',utt);
far = 1-hr(fa); hr(fa) = []; utt(fa) = []; ur(fa) = [];

plot(ax,1:length(hr),hr,'-ob');

set(ax,'XTick',1:length(utt),'XTickLabel',utt, ...
    'Xlim',[0.5 length(utt)+0.5],'YLim',[-0.1 1.1]);

% Plot false alram rate and uncertain response on top of hit rate
hold(ax,'on');
plot(ax,xlim(ax),[far far],'--r', ...
    1:length(ur),ur,':sc');
hold(ax,'off');

xlabel(ax,'Stimulus'); ylabel(ax,'Response Rate');

function tt = decodetrial(t,kk)

b1 = t{kk(1)};
b2 = t{kk(2)};

[p,n1,ext] = fileparts(b1); %#ok<NASGU,ASGLU>
[p,n2,ext] = fileparts(b2); %#ok<NASGU,ASGLU>

if ~strcmp('BB',n1)
    p = find(n1 == 'H');
    n1 = n1(3:p-1);
    j = n1;
end

if ~strcmp('BB',n2)
    p = find(n2 == 'H');
    n2 = n2(3:p-1);
    j = n2;
end

if strcmp(n1,n2)
    tt = 'CT';
else
    tt = j;
end
